package com.ari.actions;

import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

import ari.com.eft.epp.namespace.EPPSupportedExtensions;

import com.devicemantra.coordinate.dao.Settings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class EPPDViewServersAction {

	static final Logger logger = Logger.getLogger(EPPDViewServersAction.class);

	@Expose
	@SerializedName("eppd_servers")
	private List<Settings> eppdServerlist = null;
	private SessionFactory sessionFactory;

	public EPPDViewServersAction() {
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(final SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/**
	 * @return
	 */
	@Transactional
	public String execute() {
		logger.info("********[view settings]*************" + this);
		/* Query the db now */
		try {
			final Session session = sessionFactory.getCurrentSession();
			final Query query = session.createQuery("from Settings");
			// .createQuery("from Settings where friendlyName = :name");
			// query.setParameter("name", "shameem");
			eppdServerlist = query.list();
			final Iterator<Settings> iterator = eppdServerlist.iterator();
			for (final Settings item : eppdServerlist) {
				System.out.println("item " + item.getEppdIp());
				System.out.println("item " + item.getJksFileBytes().length);
				final String eppExtensions = item.getExtensions();
				System.out.println("EXTENSIONS " + eppExtensions);
			}

			/*
			 * final Query queryExtension = session
			 * .createQuery("from EPPExtension"); //
			 * .createQuery("from Settings where friendlyName = :name"); //
			 * query.setParameter("name", "shameem"); final List<EPPExtension>
			 * eppExts = queryExtension.list(); for (final EPPExtension
			 * eppExtension : eppExts) { System.out.println("EPP EXT " +
			 * eppExtension); }
			 */

		} catch (final HibernateException e) {
			System.out.println("Rolling back");
			e.printStackTrace();
		}
		// final Gson gson = new GsonBuilder().setPrettyPrinting().create();
		final Gson gson = new GsonBuilder()
				.excludeFieldsWithoutExposeAnnotation().create();
		System.out
				.println("JSON Representation " + gson.toJson(eppdServerlist));
		return "view";
	}

	public List<Settings> getEppdServerList() {
		System.out.println("Getter called now");
		return eppdServerlist;
	}

	public List<String> getExtensionsList() {
		return EPPSupportedExtensions.getList();
	}

	public void validate() {
	}

}
